#!/usr/bin/env python
# -*- coding: utf-8 -*-

from utils import log
from sqlalchemy.orm import mapper, sessionmaker
from datetime import datetime
from sqlalchemy import Table, MetaData, Column, ForeignKey, Integer, BigInteger, String, Unicode, UnicodeText, DateTime
from controls.data_pool_mysql import engine

metadata = MetaData()
Session = sessionmaker()
Session.configure(bind=engine)

"""feedback collection has
   id:          id (int)
   contact:     联系方式 (str)
   content:     内容（str）
   ctime:       注册时间(datetime)
"""


class FeedBackItem(object):

    def to_dict(self):
        res = {}
        res['contact'] = self.contact
        res['content'] = self.content
        res['ctime'] = self.ctime
        return res

    def __repr__(self):
        return "%d" % (self.content)


feedback_table = Table(
    'feedback', metadata,
    Column('id', Integer, primary_key=True, autoincrement=True),
    Column('contact', Unicode(191), nullable=True),
    Column('content', UnicodeText, nullable=False),
    Column('ctime', DateTime, default=datetime.now, nullable=False),
)

mapper(FeedBackItem, feedback_table)


def create_feedback_table_if_not_exist():
    metadata.create_all(engine)

def add_feedback_item(p_item):
    item = FeedBackItem()
    item.contact = p_item['contact']
    item.content = p_item['content']
    try:
        session = Session()
        session.add(item)
        session.flush()
        session.commit()
        return True
    except Exception as e:
        log.exp(e)
        session.rollback()
        return False
    finally:
        session.close()

def get_feedback(p_begin, p_limit):
    try:
        session = Session()
        items = session.query(FeedBackItem).order_by(FeedBackItem.ctime.desc()).offset(p_begin).offset(p_limit).all()
        result = [item.to_dict for item in items]
        return result
    except Exception as e:
        log.exp(e)
        session.rollback()
        return False
    finally:
        session.close()

if __name__ == "__main__":
    create_feedback_table_if_not_exist()
